package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;

/**
 * @author xiaoxu
 * @description:
 * @date 2024/08/23 07:24
 **/
@Slf4j
@Service
@SuppressWarnings("all")
public class FileUploadServiceImpl implements FileUploadService {



    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioConstantProperties props;

    @Override
    public String fileUpload(MultipartFile file) {
        //判断是否是图片
        try {
            BufferedImage read = ImageIO.read(file.getInputStream());
            if (read == null) {
                throw new RuntimeException("文件格式不正确");
            }

            //生成带日期  +　唯一的图片路径  防止重复
            //2024-08-23/8dde905b-2340-4ff4-955f-98000eb31d16.png
            String folder = DateUtil.today();
            String onlyName = IdUtil.randomUUID();
            String extraName = FileUtil.extName(file.getOriginalFilename());

            String objectName = "/" + folder + "/" + onlyName + "." + extraName;

            //3.调用上传文件方法
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(props.getBucketName()).object(objectName)
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());
            String finalUrl = props.getEndpointUrl() + "/" + props.getBucketName() + objectName;
            return finalUrl;
        } catch (Exception e) {
            log.error("专辑服务文件上传失败的的原因{}",e);
            throw new RuntimeException("文件上传失败");
        }
    }
}

